﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using ASoft.Base;
using System.Data;

namespace ASoft.Repository
{
    public class ASoftDataRepository : ARepository<ASoftDataEntity>
    {
        protected override string GetInsertSql(ASoftDataEntity entity)
        {
            return string.Format("insert into ASoftData(RecordTypeId,RecordKey,RecordTime,RecordData) values({0},{1},'{2}','{3}')",
                entity.RecordTypeId,
                entity.RecordKey,
                entity.RecordTime,
                entity.RecordData);

        }

        public override List<ASoftDataEntity> GetEntities(Dictionary<string, string> condition)
        {
            var sql = "select RecordTypeId,RecordKey,RecordTime,RecordData from ASoftData where 1=1";
            if (condition.ContainsKey("RecordTypeId"))
            {
                sql += " and RecordTypeId=" + condition["RecordTypeId"];
            }
            if (condition.ContainsKey("RecordTime"))
            {
                var ary = condition["RecordTime"].Split(':');
                sql += string.Format(" and RecordTime>=#{0}# and RecordTime<=#{1}#", ary[0], ary[1]);
            }
            sql += " order by RecordTime desc";
            var result = new List<ASoftDataEntity>();
            OleDbCommand command = new OleDbCommand(sql, Conn);
            if (Conn.State != System.Data.ConnectionState.Open)
            {
                Conn.Open();
            }
            int i = 0;
            var reader = command.ExecuteReader(CommandBehavior.CloseConnection);
            while (reader.Read())
            {
                var entity = new ASoftDataEntity()
                {
                    RecordTypeId = reader.GetInt16(0),
                    RecordKey = reader.GetInt16(1),
                    RecordTime = reader.GetDateTime(2),
                    RecordData = reader.GetString(3)
                };
                result.Add(entity);
                i++;
                if (i > 100)
                {
                    break;
                }
            }
            Conn.Close();
            return result;
        }

        public override string DBFileName
        {
            get
            {
                if (string.IsNullOrWhiteSpace(base.DBFileName))
                {
                    base.DBFileName = "dblog";
                }
                return base.DBFileName;
            }
            set
            {
                base.DBFileName = value;
            }
        }
    }
}
